<?php


namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\Withdraw;
use Illuminate\Http\Request;

class WithdrawController extends BaseController
{

    public function index(Request $request) {
        $user_id = $this->getUserId();
        $search = ['audit_status' => -1];
        $input = $request->input();
        $users = Withdraw::with('bank')->where('user_id', $user_id)->apply($search, $input)
            ->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));
        return $this->paginate($users);
    }

    public function apply(Request $request) {
        $user = $this->getUser();
        $user_id = $user->id;
        $this->validate($request, [
            'amount' => 'required',
            'realname' => 'required',
            'bank_id' => 'required',
            'bank_card' => 'required',
        ]);
        $input = $request->input();
        $date = date('Y-m-d');
        $exist = Withdraw::where('user_id', $user_id)->where('date', $date)->exists();
        if ($exist)
            return $this->failed('今日已申请');

        $audit_exist = Withdraw::where('user_id', $user_id)->whereIn('status', [0, 1])->exists();
        if ($audit_exist)
            return $this->failed('存在未审批的单子');

        $amount = \request('amount');
        if ($amount > 10000)
            return $this->failed('单日最多提现1万');

        $amount_fen = $amount * 100;
        if ($amount_fen > $user->balance) {
            return $this->failed('提现金额大于账户余额');
        }

        $data = [
            'trade_no' => create_order_no('t'),
            'amount' => $amount_fen,
            'user_id' => $user_id,
            'date' => $date,
            'balance' => $user->balance,
            'realname' => $input['realname'],
            'bank_id' => $input['bank_id'],
            'bank_card' => $input['bank_card'],
        ];
        Withdraw::create($data);
        return $this->success(['trade_no' => $data['trade_no']], '申请成功');
    }



}

